package com.sq.goodline.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.sq.goodline.controller.dto.AccessTokenDto;
import com.sq.goodline.controller.dto.AxBindingDto;
import com.sq.goodline.controller.dto.ResultDto;
import com.sq.goodline.dao.AxBindingDao;
import com.sq.goodline.dao.po.AxBinding;
import com.sq.goodline.util.DateUtils;
import com.sq.goodline.util.http.HttpClientUtil;
import com.sq.goodline.util.http.HttpRequest;
import com.sq.goodline.util.http.HttpResult;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class AxBingdingService {

	
	@Autowired
	AxBindingDao axBindingDao;
	@Autowired
	AccessTokenService accessTokenService; 
	@Autowired
	HttpClientUtil httpClientUtil;
	
	/**
	 * ax长绑定30天
	 * @throws Exception 
	 */
	public void axBindingJob() throws Exception{
		QueryWrapper<AxBinding> qw = new QueryWrapper<>();
		qw.eq("bind_status", 0);//0初始，1绑定，2解绑
		qw.last(" or effect_end_time<sysdate() LIMIT 10"); //ax接口最多支持10笔
		List<AxBinding> axList = axBindingDao.selectList(qw);
		if(axList==null||axList.size()==0) {
			log.debug("无待ax长绑定数据");
			return;
		}
		log.info("ax绑定开始，数量：{}",axList.size()); 
		Date d = new Date();
		Date d2 = DateUtils.addDays(d, 30);//长绑定30天
		String endTime = DateUtils.formatDate(d2, "yyyy-MM-dd HH:mm:ss");
		List<AxBindingDto> toAxBindList = new ArrayList<>();
		for(AxBinding axbind:axList) {
			AxBindingDto dto = new AxBindingDto();
			dto.setCallBack("1");//是否支持回拨,（0 是，1 否）
			dto.setCallNumA(axbind.getCallNumA());
			dto.setCallNumX(axbind.getCallNumX());
			dto.setEffectEndTime(endTime);
			toAxBindList.add(dto);
		}
		//发起绑定
		ResultDto<List<AxBindingDto>> resultDto = doAxBinding(toAxBindList);
		if("0".equals(resultDto.getReturnCode()) && resultDto.getSysCode()==0) {
			List<AxBindingDto> bindedList = resultDto.getResBody();
			for(AxBinding axbind:axList) {
				for(AxBindingDto binded:bindedList) {
					if(axbind.getCallNumX().equals(binded.getCallNumX())) {
						axbind.setBindId(binded.getBindId());
						axbind.setBindStatus(1);//绑定成功
						axbind.setEffectEndTime(DateUtils.formatTime(binded.getEffectEndTime()));
						axbind.setEffectStartTime(DateUtils.formatTime(binded.getEffectStartTime()));
						int a = axBindingDao.updateById(axbind);
						log.info("更新ax绑定结果：{}-{}",axbind.getCallNumX(),a);
					}
				}
			}
		}else {
			log.info("ax绑定失败：{}",resultDto.getMsg());
		}
	}
	
	private ResultDto<List<AxBindingDto>> doAxBinding(List<AxBindingDto> dtoList) throws Exception {
		AccessTokenDto tokenDto = accessTokenService.accessToken();
		String token = tokenDto.getResult().getAccess_token();
		String url ="http://223.255.252.183:30001/gw/bind/insert/binding/insertWorkAXN?access_token="+token;
		
		String jsonStr = JSON.toJSONString(dtoList);
				
		HttpRequest httpRequest = new HttpRequest();
		Map<String, String> headMap = new HashMap<>();
		headMap.put("x-request-id", UUID.randomUUID().toString().replace("-",""));
		headMap.put("Connection", "keep-alive");
		headMap.put("Content-Type", "application/json");
		httpRequest.setHeadMap(headMap);
		httpRequest.setRequestBody(jsonStr);
		httpRequest.setUrl(url);
		
		log.info("ax绑定http请求信息：{}",JSON.toJSONString(httpRequest));
		HttpResult httpResult = httpClientUtil.doHttpPost(httpRequest);
		
		if(200!=httpResult.getStatusCode()){
			log.error("ax绑定失败，状态码：{}",httpResult.getStatusCode());
			return null;
		}else {
			String responseJson = httpResult.getContent();
			log.info("ax绑定响应报文：{}",responseJson);
			ResultDto<JSONArray> resultDto = JSON.parseObject(responseJson, ResultDto.class);
			List<AxBindingDto> bindedList = JSONArray.parseArray(resultDto.getResBody().toString(),AxBindingDto.class);
			
			ResultDto<List<AxBindingDto>> returnDto=new ResultDto<>();
			returnDto.setMsg(resultDto.getMsg());
			returnDto.setSysCode(resultDto.getSysCode());
			returnDto.setReturnCode(resultDto.getReturnCode());
			returnDto.setResBody(bindedList);
			return returnDto;
		}
	}
	
	
	
	/**
	 * ax解绑
	 * @throws Exception 
	 */
	public void axRemoveJob() throws Exception{
		QueryWrapper<AxBinding> qw = new QueryWrapper<>();
		qw.eq("bind_status", 3);//0初始待绑定，1绑定，2解绑,3待解绑
		qw.last("LIMIT 10");  
		List<AxBinding> axList = axBindingDao.selectList(qw);
		if(axList==null||axList.size()==0) {
			log.debug("无待ax解绑定数据");
			return;
		}
		log.info("ax解绑开始，数量：{}",axList.size());
		for(AxBinding bd: axList) {
			doAxRemove(bd.getCallNumX());
		}
		log.info("ax解绑完成");
	}
	
	/**
	 * ax解绑，输入x号码
	 * @param callNumX
	 * @return
	 */
	public String doAxRemove(String callNumX) {
		try {
			AccessTokenDto tokenDto = accessTokenService.accessToken();
			String token = tokenDto.getResult().getAccess_token();
			String url ="http://223.255.252.183:30001/gw/bind/remove/binding/removeWorkAXN?access_token="+token;
			String jsonStr="[{\"callNumX\": \""+callNumX+"\"}]";
			
			HttpRequest httpRequest = new HttpRequest();
			Map<String, String> headMap = new HashMap<>();
			headMap.put("x-request-id", UUID.randomUUID().toString().replace("-",""));
			headMap.put("Connection", "keep-alive");
			headMap.put("Content-Type", "application/json");
			httpRequest.setHeadMap(headMap);
			httpRequest.setRequestBody(jsonStr);
			httpRequest.setUrl(url);
			
			log.info("ax解绑http请求信息：{}",JSON.toJSONString(httpRequest));
			HttpResult httpResult = httpClientUtil.doHttpPost(httpRequest);
			
			if(200!=httpResult.getStatusCode()){
				log.error("ax解绑失败，状态码：{}",httpResult.getStatusCode());
				return "ax解绑失败，状态码："+httpResult.getStatusCode();
			}else {
				String responseJson = httpResult.getContent();
				log.info("ax解绑响应报文：{}",responseJson);
				ResultDto<JSONArray> resultDto = JSON.parseObject(responseJson, ResultDto.class);
				if("0".equals(resultDto.getReturnCode()) && resultDto.getSysCode()==0) {
					UpdateWrapper<AxBinding> uw = new UpdateWrapper<>();
					uw.set("bind_status", 2)
					.eq("call_num_x", callNumX);
					
					int a = axBindingDao.update(null, uw);
					log.info("更新解绑状态完成：{}",a);
				}
				return responseJson;
			}
		}catch(Exception e) {
			log.error("ax解绑异常：",e);
			return e.getMessage();
		}
	}
}
